// 判断是否iphonex系列机型
export function isIphoneX() {
  return (
    (/iphone/gi.test(navigator.userAgent) &&
      Number(window.screen.height) === 812 &&
      Number(window.screen.width) === 375) ||
    (Number(window.screen.height) === 896 && Number(window.screen.width) === 414)
  )
}

// 判断是否是 app 再进行相应的页面跳转
export function pageJump({ router, target = '', opt = {} }) {
  const { lz, location } = window

  if (!router && !target) {
    throw new Error('pageJump 参数缺乏')
  }

  if (lz.isApp) {
    const { origin, pathname } = location
    // 判断是否为项目内跳转
    if (
      target.indexOf('www') === -1 &&
      target.indexOf('http') === -1 &&
      target.indexOf('devoffice') === -1 &&
      target !== '-1'
    ) {
      //  拿到URL前缀 进行拼接
      target = `${origin}${pathname}#${target}`
    }

    // 关闭当前 webview
    if (target === '-1') {
      lz.closeWebView()
    } else {
      console.info(
        JSON.stringify({
          extraData: {
            url: target,
            ...opt,
          },
        }),
      )

      lz.toAction({
        action: {
          type: 6,
          scheme: 'common/webView',
          extraData: {
            url: target,
            ...opt,
          },
        },
      })
    }
  } else {
    // 路由回退
    if (target.indexOf('zyapp.cn') !== -1 || target.indexOf('tiyalive.com') !== -1) {
      window.location.href = target
    } else if (target === '-1') {
      router.goBack()
    } else {
      router.push(target)
    }
  }
}

// 节流
export function throttle(fun, delay) {
  let last, deferTimer
  return function (args) {
    let that = this
    let _args = arguments
    let now = +new Date()
    if (last && now < last + delay) {
      clearTimeout(deferTimer)
      deferTimer = setTimeout(function () {
        last = now
        fun.apply(that, _args)
      }, delay)
    } else {
      last = now
      fun.apply(that, _args)
    }
  }
}

/**
 * json化url参数
 * @param {String}} ?后参数
 */
export function parseUrl(scene) {
  let mUrl = {}
  try {
    let strParam = scene.split('?')[1]
    let arrParamPart = strParam.split('&')
    for (let i in arrParamPart) {
      let strParamPart = arrParamPart[i]
      let arrParamKy = strParamPart.split('=')
      let strKey = arrParamKy[0]
      let strValue = decodeURIComponent(arrParamKy[1])
      mUrl[strKey] = strValue
    }
  } catch (e) {}
  return mUrl
}

// 调用客户端提供的打点接口埋点
export function gioReport(eventName, extraData = null) {
  let reportData = null
  if (extraData) {
    reportData = {
      eventName,
      extraData,
    }
  } else {
    reportData = {
      eventName,
    }
  }
  console.info(reportData)
  window.lz.traceReport(reportData).then((ret) => {
    console.info(`${eventName}打点`, ret)
  })
}

// seconds 秒
export function formatTime(seconds) {
  if (seconds <= 60) return `${seconds}''`
  let second = seconds % 60
  let min = (seconds - second) / 60
  second = second < 10 ? `0${second}` : second
  return `${min}'${second}''`
}

export function formatTime2(seconds) {
  let second = seconds % 60
  let min = (seconds - second) / 60
  min = min < 10 ? `0${min}` : min
  second = second < 10 ? `0${second}` : second
  return `${min}:${second}`
}

export const resizePortrait = (imgUrl, width = 150, height = 150) => {
  if (/[cdnimg|cdnoffice]/.test(imgUrl)) {
    return imgUrl.replace(/\.jpg$/, `_${width}x${height}.jpg`)
  }
  return imgUrl
}

// TODO: 正则不够优雅，后续优化
export const getShareUrlParamByField = ({ url, field }) => {
  const reg = new RegExp(`${field}-(.+?)\\b`, 'g')
  const matchItems = url.match(reg)
  if (matchItems && matchItems.length) {
    const lastMatchItem = matchItems[matchItems.length - 1]
    return lastMatchItem.split('-')[1]
  } else {
    return null
  }
}

// TODO: 正则不够优雅，后续优化
export const getShareUrlParams = ({ url }) => {
  const reg = new RegExp(`(?<=(=|\\*))(.+?-.+?)(?<=(\\*|\\b))`, 'g')
  const matchItems = url.match(reg)
  if (matchItems && matchItems.length) {
    return matchItems.reduce((acc, cur) => {
      const [key, value] = cur.split('-')
      acc[key] = value
      return acc
    }, {})
  } else {
    return {}
  }
}

export const wait = (delay) => {
  return new Promise((resolve) => {
    setTimeout(resolve, delay)
  })
}
